#encoding=utf-8
'''
Created on 2014-12-9

@author: cooler
'''
import sys, logging, os, os.path
import logging.handlers
import traceback
import simplejson as json
from flask import Flask, request,make_response, render_template, redirect,url_for, session, abort, current_app, g
from flask_principal import Principal, Permission, UserNeed, RoleNeed, Identity, AnonymousIdentity, identity_changed, identity_loaded


from datetime import timedelta

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 1600 * 1024 * 1024

logger = logging.getLogger()   
logfile = logging.handlers.TimedRotatingFileHandler(os.path.join(os.getcwd(), './logs/'+"test"), 'D', 1, 0)
# 设置后缀名称，跟strftime的格式一样
logfile.suffix = "%Y%m%d.log"
logger.addHandler(logfile) 

formatter = logging.Formatter("%(asctime)s - %(name)s - %(filename)s - %(funcName)s - %(levelname)s - %(process)d - Line:%(lineno)d - %(message)s")  
logfile.setFormatter(formatter)   
logger.setLevel(logging.DEBUG) 

app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
app.permanent_session_lifetime = timedelta(seconds=30*60)
# load the extension
#设置登录过期时间
# session.permanent = True
# app.permanent_session_lifetime = timedelta(minutes=1)
principals = Principal(app)

admin_permission = Permission(RoleNeed('admin'),RoleNeed('cooler'))

@identity_loaded.connect_via(app)
def on_identity_loaded(sender, identity):
    identity.user = session.get("userinfo")
    if session.get("userinfo"):
        identity.provides.add(UserNeed(session.get("userinfo")['account']))

        for role in session.get("userinfo")['roles']:
            identity.provides.add(RoleNeed(role))


@app.route("/auth", methods=['GET', 'POST'])
def auth():
    try:
        username = request.form.get('username').strip()
        password = request.form.get('password').strip()
        logger.info(username+" "+password)
        if username == "admin" and password == 'admin':
            user_info = dict()
            user_info['account'] = username
            user_info['roles'] = ['admin']
            session["userinfo"] = user_info
            identity_changed.send(current_app._get_current_object(), identity=Identity(user_info['account']))
            logger.info("user login: account - %s, roles- %s" %
                        (session.get("userinfo").get("account"), session.get("userinfo").get("roles")))
            return render_template('index.html',user_info=user_info)
        else:
            return redirect("/to_login")
 
    except Exception, e:
        app.logger.error(traceback.format_exc(e))


@app.route('/main', methods=['GET'])
@admin_permission.require(http_exception=401)
def main():
    return 'hello'


def md5(str_to_process):
    m = hashlib.md5()
    m.update(str_to_process)
    return m.hexdigest()



@app.route('/', methods=['GET'])
@app.route('/to_login', methods=['GET'])
def login():
    return render_template("login.html")


@app.route("/logout", methods=['GET'])
def logout():
    if session.get('userinfo') is not None:
        app.logger.info("user logout: account - %s, roles- %s" % (
            session.get("userinfo").get("account"), session.get("userinfo").get("roles")))
        session.pop("userinfo")
        # Remove session keys set by Flask-Principal
        for key in ('identity.name', 'identity.auth_type'):
            session.pop(key, None)

        # Tell Flask-Principal the user is anonymous
        identity_changed.send(current_app._get_current_object(), identity=AnonymousIdentity())
    return redirect("/to_login")



if __name__ == '__main__':
    app.run(host='0.0.0.0',port=8081,debug=True)
